import axios, { AxiosInstance, AxiosResponse } from 'axios'
import type { 
  APIResponse, 
  LoginRequest, 
  LoginResponse, 
  User,
  ChatMessage,
  ChatHistoryResponse,
  AIResponse,
  AIQueryRequest,
  AnalyticsResponse,
  TokenStats,
  ChatSession,
  SQLLog,
  DynamicMenu
} from '@/types'

// Create axios instance
const api: AxiosInstance = axios.create({
  baseURL: 'http://192.168.11.117:5420/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 简化的401处理，直接跳转登录页

// Request interceptor to add auth token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// Response interceptor for error handling
api.interceptors.response.use(
  (response: AxiosResponse) => response,
  async (error) => {
    if (error.response?.status === 401) {
      console.log(' 401未授权错误，清理认证数据并跳转登录页')
      
      // 清理所有认证数据
      localStorage.removeItem('auth_token')
      localStorage.removeItem('user_info')
      localStorage.removeItem('current_session_id')
      
      // 跳转到登录页（避免在登录页重复跳转）
      if (window.location.pathname !== '/login' && window.location.pathname !== '/') {
        console.log(' 重定向到登录页')
        window.location.href = '/login'
      }
    }
    
    return Promise.reject(error)
  }
)

// Auth API
const authAPI = {
  // 用户登录
  login: async (data: LoginRequest): Promise<LoginResponse> => {
    const response = await api.post<LoginResponse>('/auth/login', data)
    return response.data
  },

  // 用户登出
  logout: async (): Promise<APIResponse> => {
    const response = await api.post<APIResponse>('/auth/logout')
    return response.data
  },

  // 获取当前用户信息
  getCurrentUser: async (): Promise<APIResponse<{user: User, permissions: string[]}>> => {
    const response = await api.get<APIResponse<{user: User, permissions: string[]}>>('/auth/me')
    return response.data
  },


  // 修改密码
  changePassword: async (data: { 
    oldPassword: string
    newPassword: string 
  }): Promise<APIResponse> => {
    const response = await api.post<APIResponse>('/auth/change-password', data)
    return response.data
  }
}

// Chat API
const chatAPI = {
  // 获取对话历史
  getHistory: async (params?: {
    session_id?: string
    limit?: number
    offset?: number
  }): Promise<ChatHistoryResponse> => {
    const response = await api.get<ChatHistoryResponse>('/chat/history', { params })
    return response.data
  },

  // 保存消息
  saveMessage: async (data: {
    message: string
    role: 'user' | 'assistant' | 'system'
    session_id?: string
    metadata?: Record<string, any>
  }): Promise<APIResponse<ChatMessage>> => {
    const response = await api.post<APIResponse<ChatMessage>>('/chat/messages', data)
    return response.data
  },

  // 清除对话历史
  clearHistory: async (session_id?: string): Promise<APIResponse> => {
    const response = await api.delete<APIResponse>('/chat/history', {
      params: { session_id }
    })
    return response.data
  },

  // 获取会话列表
  getSessions: async (): Promise<APIResponse<any[]>> => {
    const response = await api.get<APIResponse<any[]>>('/chat/sessions')
    return response.data
  },

  // 创建新会话
  createSession: async (data: { title?: string }): Promise<APIResponse<ChatSession>> => {
    const response = await api.post<APIResponse<ChatSession>>('/chat/sessions', data)
    return response.data
  },

  // 删除会话
  deleteSession: async (sessionId: string): Promise<APIResponse> => {
    const response = await api.delete<APIResponse>(`/chat/sessions/${sessionId}`)
    return response.data
  }
}

// AI API
const aiAPI = {
  // AI对话
  chat: async (data: AIQueryRequest): Promise<AIResponse> => {
    const response = await api.post<AIResponse>('/ai/chat', data)
    return response.data
  },

  // 智能数据查询
  query: async (data: {
    query: string
    type?: 'auto' | 'product' | 'customer' | 'order'
  }): Promise<APIResponse> => {
    const response = await api.post<APIResponse>('/ai/query', data)
    return response.data
  },

  // 业务分析
  analyze: async (data: {
    type: 'sales' | 'inventory' | 'customer' | 'all'
    dateRange?: {
      start: string
      end: string
    }
  }): Promise<AnalyticsResponse> => {
    const response = await api.post<AnalyticsResponse>('/ai/analyze', data)
    return response.data
  },

  // AI建议
  suggest: async (data: {
    context?: string
    data?: any
  }): Promise<APIResponse<{
    suggestions: string
    businessContext: any
  }>> => {
    const response = await api.post<APIResponse<{
      suggestions: string
      businessContext: any
    }>>('/ai/suggest', data)
    return response.data
  },

  // DeepSeek统计和信息
  getStats: async (days: number = 30): Promise<APIResponse<{
    total_stats: {
      total_sessions: number
      total_messages: number
      total_tokens: number
      total_sql_queries: number
      success_rate: number
      avg_execution_time: number
      estimated_cost: number
    }
    daily_stats: Array<{
      date: string
      sql_count: number
      avg_execution_time: number
      success_count: number
      failed_count: number
      message_count: number
      total_tokens: number
      session_count: number
    }>
    date_range: {
      start_date: string
      end_date: string
      days: number
    }
  }>> => {
    const response = await api.get<APIResponse<{
      total_stats: {
        total_sessions: number
        total_messages: number
        total_tokens: number
        total_sql_queries: number
        success_rate: number
        avg_execution_time: number
        estimated_cost: number
      }
      daily_stats: Array<{
        date: string
        sql_count: number
        avg_execution_time: number
        success_count: number
        failed_count: number
        message_count: number
        total_tokens: number
        session_count: number
      }>
      date_range: {
        start_date: string
        end_date: string
        days: number
      }
    }>>(`/deepseek/stats-full?days=${days}`)
    return response.data
  },
    
  getModelInfo: async (): Promise<APIResponse<{
    model_info: {
      model_name: string
      api_endpoint: string
      max_tokens: number
      temperature: number
      status: string
      version: string
      capabilities: string[]
      pricing: {
        input_tokens: number
        output_tokens: number
        currency: string
      }
      limits: {
        requests_per_minute: number
        tokens_per_minute: number
        max_context_length: number
      }
    }
    api_health: {
      status: string
      last_call: string | null
      recent_errors: number
      avg_response_time: number
    }
    recent_calls: Array<{
      execution_status: string
      execution_time: number
      created_at: string
      error_message: string | null
    }>
  }>> => {
    const response = await api.get<APIResponse<{
      model_info: {
        model_name: string
        api_endpoint: string
        max_tokens: number
        temperature: number
        status: string
        version: string
        capabilities: string[]
        pricing: {
          input_tokens: number
          output_tokens: number
          currency: string
        }
        limits: {
          requests_per_minute: number
          tokens_per_minute: number
          max_context_length: number
        }
      }
      api_health: {
        status: string
        last_call: string | null
        recent_errors: number
        avg_response_time: number
      }
      recent_calls: Array<{
        execution_status: string
        execution_time: number
        created_at: string
        error_message: string | null
      }>
    }>>('/deepseek/model-info')
    return response.data
  }
}

// Business Data API
const businessAPI = {
  // 产品管理
  products: {
    list: async (params?: any): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/products', { params })
      return response.data
    },
    get: async (id: number): Promise<APIResponse> => {
      const response = await api.get<APIResponse>(`/products/${id}`)
      return response.data
    },
    create: async (data: any): Promise<APIResponse> => {
      const response = await api.post<APIResponse>('/products', data)
      return response.data
    },
    update: async (id: number, data: any): Promise<APIResponse> => {
      const response = await api.put<APIResponse>(`/products/${id}`, data)
      return response.data
    },
    delete: async (id: number): Promise<APIResponse> => {
      const response = await api.delete<APIResponse>(`/products/${id}`)
      return response.data
    }
  },

  // 客户管理
  customers: {
    list: async (params?: any): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/customers', { params })
      return response.data
    },
    get: async (id: number): Promise<APIResponse> => {
      const response = await api.get<APIResponse>(`/customers/${id}`)
      return response.data
    },
    create: async (data: any): Promise<APIResponse> => {
      const response = await api.post<APIResponse>('/customers', data)
      return response.data
    },
    update: async (id: number, data: any): Promise<APIResponse> => {
      const response = await api.put<APIResponse>(`/customers/${id}`, data)
      return response.data
    },
    delete: async (id: number): Promise<APIResponse> => {
      const response = await api.delete<APIResponse>(`/customers/${id}`)
      return response.data
    }
  },

  // 订单管理
  orders: {
    list: async (params?: any): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/orders', { params })
      return response.data
    },
    get: async (id: number): Promise<APIResponse> => {
      const response = await api.get<APIResponse>(`/orders/${id}`)
      return response.data
    },
    create: async (data: any): Promise<APIResponse> => {
      const response = await api.post<APIResponse>('/orders', data)
      return response.data
    },
    update: async (id: number, data: any): Promise<APIResponse> => {
      const response = await api.put<APIResponse>(`/orders/${id}`, data)
      return response.data
    },
    delete: async (id: number): Promise<APIResponse> => {
      const response = await api.delete<APIResponse>(`/orders/${id}`)
      return response.data
    }
  },

  // 库存管理
  inventory: {
    list: async (params?: any): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/inventory', { params })
      return response.data
    },
    get: async (id: number): Promise<APIResponse> => {
      const response = await api.get<APIResponse>(`/inventory/${id}`)
      return response.data
    },
    update: async (id: number, data: any): Promise<APIResponse> => {
      const response = await api.put<APIResponse>(`/inventory/${id}`, data)
      return response.data
    }
  },

  // 报表统计
  reports: {
    dashboard: async (): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/reports/dashboard')
      return response.data
    },
    sales: async (params?: any): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/reports/sales', { params })
      return response.data
    },
    inventory: async (params?: any): Promise<APIResponse> => {
      const response = await api.get<APIResponse>('/reports/inventory', { params })
      return response.data
    }
  }
}

// User Management API
const userAPI = {
  // 用户列表
  list: async (params?: any): Promise<APIResponse> => {
    const response = await api.get<APIResponse>('/users', { params })
    return response.data
  },

  // 获取用户详情
  get: async (id: number): Promise<APIResponse<User>> => {
    const response = await api.get<APIResponse<User>>(`/users/${id}`)
    return response.data
  },

  // 创建用户
  create: async (data: any): Promise<APIResponse> => {
    const response = await api.post<APIResponse>('/users', data)
    return response.data
  },

  // 更新用户
  update: async (id: number, data: any): Promise<APIResponse> => {
    const response = await api.put<APIResponse>(`/users/${id}`, data)
    return response.data
  },

  // 删除用户
  delete: async (id: number): Promise<APIResponse> => {
    const response = await api.delete<APIResponse>(`/users/${id}`)
    return response.data
  },

  // 更新用户权限
  updatePermissions: async (id: number, permissions: string[]): Promise<APIResponse> => {
    const response = await api.put<APIResponse>(`/users/${id}/permissions`, { permissions })
    return response.data
  },

  // 获取用户主题配置
  getThemeConfig: async (userId: number): Promise<APIResponse<any>> => {
    const response = await api.get<APIResponse<any>>(`/users/${userId}/theme`)
    return response.data
  },

  // 保存用户主题配置
  saveThemeConfig: async (userId: number, themeConfig: any): Promise<APIResponse<any>> => {
    const response = await api.put<APIResponse<any>>(`/users/${userId}/theme`, themeConfig)
    return response.data
  }
}

// System API
const systemAPI = {
  // 获取Token使用统计
  getTokenStats: async (params?: {
    startDate?: string
    endDate?: string
  }): Promise<APIResponse<TokenStats>> => {
    const response = await api.get<APIResponse<TokenStats>>('/system/token-stats', { params })
    return response.data
  },

  // 获取系统信息
  getSystemInfo: async (): Promise<APIResponse> => {
    const response = await api.get<APIResponse>('/system/info')
    return response.data
  },

  // 健康检查
  healthCheck: async (): Promise<APIResponse> => {
    const response = await api.get<APIResponse>('/system/health')
    return response.data
  }
}

// SQL日志相关接口
const sqlLogAPI = {
  // 获取SQL日志列表
  getSQLLogs: async (params?: {
    page?: number
    limit?: number
    user_id?: number
    sql_type?: string
    execution_status?: string
    risk_level?: string
    start_date?: string
    end_date?: string
  }): Promise<APIResponse<{
    list: SQLLog[]
    pagination: {
      current: number
      pageSize: number
      total: number
      pages: number
    }
  }>> => {
    const response = await api.get<APIResponse<{
      list: SQLLog[]
      pagination: {
        current: number
        pageSize: number
        total: number
        pages: number
      }
    }>>('/sql-log', { params })
    return response.data
  },

  // 获取SQL日志详情
  getSQLLogDetail: async (id: number): Promise<APIResponse<SQLLog>> => {
    const response = await api.get<APIResponse<SQLLog>>(`/sql-log/${id}`)
    return response.data
  },

  // 审批SQL日志
  approveSQLLog: async (id: number, data: { approved: boolean; comment?: string }): Promise<APIResponse> => {
    const response = await api.patch<APIResponse>(`/sql-log/${id}/approve`, data)
    return response.data
  },

  // 删除SQL日志
  deleteSQLLog: async (id: number): Promise<APIResponse> => {
    const response = await api.delete<APIResponse>(`/sql-log/${id}`)
    return response.data
  },

  // 获取SQL日志统计
  getSQLLogStats: async (params?: {
    start_date?: string
    end_date?: string
  }): Promise<APIResponse<{
    total: number
    statusStats: { [key: string]: number }
    sqlTypeStats: { [key: string]: number }
    riskLevelStats: { [key: string]: number }
    topUsers: Array<{ user_id: number; username: string; realName: string; count: number }>
  }>> => {
    const response = await api.get<APIResponse<{
      total: number
      statusStats: { [key: string]: number }
      sqlTypeStats: { [key: string]: number }
      riskLevelStats: { [key: string]: number }
      topUsers: Array<{ user_id: number; username: string; realName: string; count: number }>
    }>>('/sql-log/stats/summary', { params })
    return response.data
  }
}

// 动态菜单相关接口
const dynamicMenuAPI = {
  // 获取所有动态菜单
  getMenus: async (): Promise<APIResponse<DynamicMenu[]>> => {
    const response = await api.get<APIResponse<DynamicMenu[]>>('/dynamic-menu')
    return response.data
  },

  // 创建动态菜单
  createMenu: async (data: {
    name: string
    key: string
    icon?: string
    table_name: string
    description?: string
    permissions?: string[]
    columns_config?: any
    sort_order?: number
  }): Promise<APIResponse<DynamicMenu>> => {
    const response = await api.post<APIResponse<DynamicMenu>>('/dynamic-menu', data)
    return response.data
  },

  // 更新动态菜单
  updateMenu: async (id: number, data: Partial<DynamicMenu>): Promise<APIResponse<DynamicMenu>> => {
    const response = await api.put<APIResponse<DynamicMenu>>(`/dynamic-menu/${id}`, data)
    return response.data
  },

  // 删除动态菜单
  deleteMenu: async (id: number): Promise<APIResponse> => {
    const response = await api.delete<APIResponse>(`/dynamic-menu/${id}`)
    return response.data
  },

  // 获取表数据
  getTableData: async (tableName: string, params?: {
    page?: number
    limit?: number
    search?: string
    sort_field?: string
    sort_order?: string
  }): Promise<APIResponse<{
    list: any[]
    pagination: {
      current: number
      pageSize: number
      total: number
      pages: number
    }
  }>> => {
    const response = await api.get<APIResponse<{
      list: any[]
      pagination: {
        current: number
        pageSize: number
        total: number
        pages: number
      }
    }>>(`/dynamic-menu/table-data/${tableName}`, { params })
    return response.data
  },

  // AI菜单控制已集成到聊天中，通过SQL直接执行

  // 获取表结构
  getTableStructure: async (tableName: string): Promise<APIResponse<{
    columns: Array<{
      field: string
      type: string
      null: boolean
      key: string
      default: any
      extra: string
    }>
  }>> => {
    const response = await api.get<APIResponse<{
      columns: Array<{
        field: string
        type: string
        null: boolean
        key: string
        default: any
        extra: string
      }>
    }>>(`/dynamic-menu/table-structure/${tableName}`)
    return response.data
  },

  // 动态表CRUD操作
  createRecord: async (tableName: string, data: any): Promise<APIResponse> => {
    const response = await api.post<APIResponse>(`/dynamic-menu/table-data/${tableName}`, data)
    return response.data
  },

  updateRecord: async (tableName: string, id: number, data: any): Promise<APIResponse> => {
    const response = await api.put<APIResponse>(`/dynamic-menu/table-data/${tableName}/${id}`, data)
    return response.data
  },

  deleteRecord: async (tableName: string, id: number): Promise<APIResponse> => {
    const response = await api.delete<APIResponse>(`/dynamic-menu/table-data/${tableName}/${id}`)
    return response.data
  },

  getRecord: async (tableName: string, id: number): Promise<APIResponse> => {
    const response = await api.get<APIResponse>(`/dynamic-menu/table-data/${tableName}/${id}`)
    return response.data
  }
}

// Export the main api instance and specific services needed
export default api
export { authAPI, chatAPI, aiAPI, businessAPI, userAPI, systemAPI, sqlLogAPI, dynamicMenuAPI }
